package com.ztf666.service.impl;

import com.ztf666.service.DocService;
import com.ztf666.utils.ConnectionUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @Author ztf
 * @Date 21:05 2022/1/17
 **/
public class DocServiceImpl implements DocService {
    @Override
    public void addDoc(String index, String source) throws IOException {
        RestHighLevelClient restHighLevelClient = ConnectionUtils.getClient();
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.source(source, XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    @Override
    public void addDocWithId(String index, String id, String source) throws IOException {
        RestHighLevelClient highLevelClient = ConnectionUtils.getClient();
        IndexRequest indexRequest = new IndexRequest(index);
        //手动设置id
        indexRequest.id(id);
        //设置要添加的数据以及格式为json
        indexRequest.source(source, XContentType.JSON);
        IndexResponse response = highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    @Override
    public void updateDoc(String index, String id, String source) throws Exception {
        RestHighLevelClient highLevelClient = ConnectionUtils.getClient();
        UpdateRequest updateRequest=new UpdateRequest(index,id);
        updateRequest.doc(source, XContentType.JSON);
        UpdateResponse response = highLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    @Override
    public void deleteDoc(String index, String id) throws Exception {
        RestHighLevelClient highLevelClient = ConnectionUtils.getClient();
        DeleteRequest deleteRequest = new DeleteRequest(index, id);
        DeleteResponse response = highLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }
}
